//
//  WMMusicRequestNetease.m
//  WholeMusic
//
//  Created by quanxiong on 2018/3/4.
//  Copyright © 2018年 quanxiong. All rights reserved.
//

#import "WMMusicRequestNetease.h"
#import <YYKit/YYKit.h>
#import "NSData+WMUtils.h"

@implementation WMMusicRequestNetease

- (AFHTTPSessionManager *)searchManager {
    AFHTTPSessionManager *manager = [self managerForBaseURL:@"http://music.163.com"];
    [manager.requestSerializer setValue:@"http://music.163.com/" forHTTPHeaderField:@"Referrer"];
//    [manager.requestSerializer setValue:@"okhttp/3.9.1" forHTTPHeaderField:@"User-Agent"];
    return manager;
}

- (AFHTTPSessionManager *)updateVKeyManager {
    AFHTTPSessionManager *manager = [self managerForBaseURL:@"http://base.music.qq.com"];
    [manager.requestSerializer setValue:@"http://y.qq.com" forHTTPHeaderField:@"Referrer"];
//    [manager.requestSerializer setValue:s_userAgent forHTTPHeaderField:@"User-Agent"];
    return manager;
}

- (NSString *)encryptedForJson:(NSDictionary *)json {
    NSString *jsonString = [json jsonStringEncoded];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *SECRET = @"7246674226682325323F5E6544673A51";
    NSData *keyData = [NSData dataWithHexString:SECRET];
    NSData *encryptedData = [jsonData AES128EncryptWithKey:keyData];
    NSString *encrypted = [encryptedData hexString].uppercaseString;
    return encrypted;
}

- (void)searchMusicWithKeyaord:(NSString *)keyword complete:(void(^)(id response))complete {
    if (keyword.length == 0) {
        if (complete) {
            complete(nil);
        }
        return;
    }
    NSMutableDictionary *json = [@{@"method":@"POST",
                                   @"url":@"http://music.163.com/api/cloudsearch/pc"
                                   } mutableCopy];
    //TODO: 分页参数
    NSInteger limit = 50;
    NSInteger offset = 0 * limit;
    
    NSMutableDictionary *params = [@{@"s":keyword,
                                     @"type":@1,
                                     @"offset":@(offset),
                                     @"limit":@(limit)
                                     } mutableCopy];
    json[@"params"] = params;
    
    NSString *encrypted = [self encryptedForJson:json];
    
    [self.searchManager POST:@"/api/linux/forward"
                  parameters:@{@"eparams":encrypted}
                    progress:nil
                     success:
     ^(NSURLSessionDataTask *task, id responseObject) {
         NSLog(@"%@", responseObject);
         if (complete) {
             complete(responseObject);
         }
     } failure:^(NSURLSessionDataTask * task, NSError * error) {
         NSLog(@"%@", error);
         if (complete) {
             complete(nil);
         }
     }];
}

@end
